from machine import SPI, Pin
from machine import I2C
from paj7620u2 import PAJ7620U2
import st7789
import utime
import network
import urequests
import ujson
import gc

spi = SPI(0, baudrate=40000000, polarity=1, phase=0, bits=8, endia=0, sck=Pin(6), mosi=Pin(8))
display = st7789.ST7789(spi, 240, 240, reset=Pin(11,func=Pin.GPIO, dir=Pin.OUT), dc=Pin(7,func=Pin.GPIO, dir=Pin.OUT))
display.init()
i2c = I2C(1, sda=Pin(0), scl=Pin(1), freq=400000)

def keepdraw(checkerboard,color,x,y,i,j):
    display.fill_rect(x, y, 75, 75,color)
    if checkerboard[i][j]==1:
        display.fill_circle(37+x, 37+y, 25,st7789.color565(0, 0, 0))
        display.fill_circle(37+x, 37+y, 20,color)
    elif checkerboard[i][j]==2:
        display.draw_string(x+20, y+8, str3, color=st7789.BLACK, bg=color, size=7, vertical=False, rotate=st7789.ROTATE_0, spacing=1)

def start():
    while True:
        if sensor7620.print_gesture()==5:
            break
    utime.sleep_ms(1000)
    display.fill_rect(0, 0, 240, 240,st7789.color565(255,255,255))
    display.fill_rect(0, 75, 240, 5, st7789.color565(0, 0, 0))
    display.fill_rect(0, 155, 240, 5, st7789.color565(0, 0, 0))
    display.fill_rect(0, 235, 240, 5, st7789.color565(0, 0, 0))
    display.fill_rect(75, 0, 5, 240, st7789.color565(0, 0, 0))
    display.fill_rect(155, 0, 5, 240, st7789.color565(0, 0, 0))
    display.fill_rect(235, 0, 5, 240, st7789.color565(0, 0, 0))
    display.fill_rect(0, 0, 75, 75,st7789.color565(255,165,0))

def againgame():
    str6='ANOTHER GAME'
    str7='BY CLOCKWISE GESTURE'
    utime.sleep_ms(1000)
    display.fill_rect(0, 0, 240, 240,st7789.color565(0,0,0))
    display.draw_string(15, 90, str6, color=st7789.WHITE, bg=st7789.color565(0, 0, 0), size=3, vertical=False, rotate=st7789.ROTATE_0, spacing=1)
    display.draw_string(15, 140, str7, color=st7789.WHITE, bg=st7789.color565(0, 0, 0), size=2, vertical=False, rotate=st7789.ROTATE_0, spacing=1)
    start()

def connectWIFI():
    print('Connecting wifi...')
    sta_wlan = network.WLAN(network.STA_IF)
    sta_wlan.active(True)
    sta_wlan.connect('Brooke', '12345678', security=network.AUTH_PSK)
    while(sta_wlan.config() == '0.0.0.0'):
        utime.sleep(1)
    print('Connected...')

p1score=0
p2score=0
connectWIFI()
utime.sleep(3)
def upload(p1score,p2score):
    url = "http://post.blackwalnut.zucc.edu.cn/thingswise/idos/jets/streams/dev/32101190/Game___GameData.GameData_input_json"
    headers = {
        "content-type": "application/json",
    }
    formData = {
        'data':{
            "case": "GAME",
            "data": "instance1"
        },
        'auth':{
            'user': 'zucc',
            'password': '123456'
        }
    }
    try:
        P1score=p1score
        P2score=p2score
        formData['data']['P1score'] = P1score
        formData['data']['P2score'] = P2score
        res = urequests.post(url, data=ujson.dumps(formData),headers=headers)
        print(res.status_code)
        print(res.text)
    except Exception as err:
        print(err)
    gc.collect()
    utime.sleep(1)

str1='START GAME'
str2='BY CLOCKWISE GESTURE'
str3='x'
display.fill_rect(0, 0, 240, 240,st7789.color565(0,0,0))
display.draw_string(15, 90, str1, color=st7789.WHITE, bg=st7789.color565(0, 0, 0), size=4, vertical=False, rotate=st7789.ROTATE_0, spacing=2)
display.draw_string(15, 140, str2, color=st7789.WHITE, bg=st7789.color565(0, 0, 0), size=2, vertical=False, rotate=st7789.ROTATE_0, spacing=1)

#识别到顺时针手势开始游戏界面
sensor7620=PAJ7620U2(i2c)
start()
checkerboard = [[0 for i in range(5)] for j in range(5)]
i=1
j=1
x=0
y=0
utime.sleep_ms(2000)

P1 = Pin(2)
P2 = Pin(14)
P1.init(Pin.IN)
P2.init(Pin.IN)
P1.pull(Pin.PULL_DOWN)
P2.pull(Pin.PULL_DOWN)

flag=0
sum=0
while True:
    while True:
        if P1.value()==1 or P2.value()==1:
            if P1.value()==1:
                if checkerboard[i][j]==0:
                    display.fill_circle(37+x, 37+y, 25,st7789.color565(0, 0, 0))
                    display.fill_circle(37+x, 37+y, 20,st7789.color565(255,165,0))
                    checkerboard[i][j]=1
                    sum=sum+1
                    cnt1=0
                    cnt2=0
                    cnt3=0
                    cnt4=0
                    checkerboard[i][j]=1
                    if i==j:
                        for k in range(4):
                            if checkerboard[k][k]==1:
                                cnt1=cnt1+1
                    if (i+j)==4:
                        for k in range(4):
                            if checkerboard[k][4-k]==1:
                                cnt2=cnt2+1
                    for k in range(4):
                        if checkerboard[i][k]==1:
                            cnt3=cnt3+1
                    for k in range(4):
                        if checkerboard[k][j]==1:
                            cnt4=cnt4+1
                    if cnt1==3 or cnt2==3 or cnt3==3 or cnt4==3:
                        str4='Player1 win'
                        display.fill_rect(0, 0, 240, 240,st7789.color565(0,0,0))
                        display.draw_string(5, 90, str4, color=st7789.WHITE, bg=st7789.color565(0, 0, 0), size=4, vertical=False, rotate=st7789.ROTATE_0, spacing=1)
                        utime.sleep_ms(2000)
                        checkerboard = [[0 for i in range(5)] for j in range(5)]
                        i=1
                        j=1
                        x=0
                        y=0
                        flag=0
                        sum=0
                        p1score=p1score+1
                        upload(p1score,p2score)
                        againgame()
                        break
                    elif sum==9:
                        str6='Draw'
                        display.fill_rect(0, 0, 240, 240,st7789.color565(0,0,0))
                        display.draw_string(75, 90, str6, color=st7789.WHITE, bg=st7789.color565(0, 0, 0), size=5, vertical=False, rotate=st7789.ROTATE_0, spacing=3)
                        utime.sleep_ms(2000)
                        checkerboard = [[0 for i in range(5)] for j in range(5)]
                        i=1
                        j=1
                        x=0
                        y=0
                        flag=0
                        sum=0
                        againgame()
                        break
            elif P2.value()==1:
                if checkerboard[i][j]==0:
                    display.draw_string(x+20, y+8, str3, color=st7789.BLACK, bg=st7789.BLACK, size=7, vertical=False, rotate=st7789.ROTATE_0, spacing=1)
                    checkerboard[i][j]=2
                    sum=sum+1
                    cnt1=0
                    cnt2=0
                    cnt3=0
                    cnt4=0
                    checkerboard[i][j]=2
                    if i==j:
                        for k in range(4):
                            if checkerboard[k][k]==2:
                                cnt1=cnt1+1
                    if (i+j)==4:
                        for k in range(4):
                            if checkerboard[k][4-k]==2:
                                cnt2=cnt2+1
                    for k in range(4):
                        if checkerboard[i][k]==2:
                            cnt3=cnt3+1
                    for k in range(4):
                        if checkerboard[k][j]==2:
                            cnt4=cnt4+1
                    if cnt1==3 or cnt2==3 or cnt3==3 or cnt4==3:
                        str5='Player2 win'
                        display.fill_rect(0, 0, 240, 240,st7789.color565(0,0,0))
                        display.draw_string(5, 90, str5, color=st7789.WHITE, bg=st7789.color565(0, 0, 0), size=4, vertical=False, rotate=st7789.ROTATE_0, spacing=1)
                        utime.sleep_ms(2000)
                        checkerboard = [[0 for i in range(5)] for j in range(5)]
                        i=1
                        j=1
                        x=0
                        y=0
                        flag=0
                        sum=0
                        p2score=p2score+1
                        upload(p1score,p2score)
                        againgame()
                        break
                    elif sum==9:
                        str6='Draw'
                        display.fill_rect(0, 0, 240, 240,st7789.color565(0,0,0))
                        display.draw_string(75, 90, str6, color=st7789.WHITE, bg=st7789.color565(0, 0, 0), size=5, vertical=False, rotate=st7789.ROTATE_0, spacing=3)
                        utime.sleep_ms(2000)
                        checkerboard = [[0 for i in range(5)] for j in range(5)]
                        i=1
                        j=1
                        x=0
                        y=0
                        flag=0
                        sum=0
                        againgame()
                        break
        else:
            flag = sensor7620.print_gesture()
            if flag != 0:
                break
    while True:
        if flag == 0:
            break
        if flag == 5:
            break
        if flag == 4:    #向下
            keepdraw(checkerboard,st7789.color565(255,255,255),x,y,i,j)
            if j<3:
                j=j+1
            else:
                j=1
            y=(y+80)%240
            keepdraw(checkerboard,st7789.color565(255,165,0),x,y,i,j)
            break
        elif flag == 3:   #向上
            keepdraw(checkerboard,st7789.color565(255,255,255),x,y,i,j)
            if j<2:
                j=3
            else:
                j=j-1
            y=(y-80+240)%240
            keepdraw(checkerboard,st7789.color565(255,165,0),x,y,i,j)
            break
        elif flag == 2:  #向左
            keepdraw(checkerboard,st7789.color565(255,255,255),x,y,i,j)
            if i<2:
                i=3
            else:
                i=i-1
            x=(x-80+240)%240
            keepdraw(checkerboard,st7789.color565(255,165,0),x,y,i,j)
            break
        elif flag == 1:   #向右
            keepdraw(checkerboard,st7789.color565(255,255,255),x,y,i,j)
            if i<3:
                i=i+1
            else:
                i=1
            x=(x+80)%240
            keepdraw(checkerboard,st7789.color565(255,165,0),x,y,i,j)
            break